<template>
  <div class="page-content">
    <ElForm :model="queryForm" :inline="true">
      <!-- 第一行：基础筛选 -->
      <ElRow :gutter="16" style="margin-bottom: 16px">
        <ElCol :xs="24" :sm="8" :md="6" :lg="18">
          <ElSpace :size="1">
            <ElFormItem label="关键字搜索">
              <ElInput
                v-model="queryForm.keyword"
                placeholder="订单号/手机号/商品名称"
                clearable
                style="min-width: 200px"
              />
            </ElFormItem>
            <ElFormItem label="订单状态">
              <ElSelect
                v-model="queryForm.status"
                placeholder="请选择状态"
                clearable
                style="width: 100%; min-width: 150px"
              >
                <ElOption label="待支付" value="pending" />
                <ElOption label="已支付" value="paid" />
                <ElOption label="已发货" value="shipped" />
                <ElOption label="已收货" value="delivered" />
                <ElOption label="已完成" value="completed" />
                <ElOption label="已取消" value="cancelled" />
                <ElOption label="已退款" value="refunded" />
                <ElOption label="退款中" value="refunding" />
              </ElSelect>
            </ElFormItem>
            <ElFormItem label="商品类型">
              <ElSelect
                v-model="queryForm.productType"
                placeholder="请选择商品类型"
                clearable
                style="width: 100%; min-width: 150px"
              >
                <ElOption label="VIP会员" value="vip" />
                <ElOption label="入场券" value="ticket" />
                <ElOption label="实物商品" value="physical" />
              </ElSelect>
            </ElFormItem>
          </ElSpace>
        </ElCol>
        <ElCol :xs="24" :sm="8" :md="6" :lg="4">
          <ElFormItem>
            <ElSpace :size="4">
              <ElButton type="primary" @click="handleSearch" v-ripple>搜索</ElButton>
              <ElButton @click="resetQuery" v-ripple>重置</ElButton>
              <ElButton type="info" @click="exportOrders" v-ripple>导出订单</ElButton>
            </ElSpace>
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>

    <ArtTable
      :data="orderList"
      :loading="loading"
      :total="pagination.total"
      v-model:current-page="pagination.page"
      v-model:page-size="pagination.size"
      :page-sizes="[10, 20, 50, 100]"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :show-pagination="true"
      :hide-on-single-page="false"
      index
    >
      <template #default>
        <ElTableColumn label="订单号" prop="orderNo" min-width="160" />
        <ElTableColumn label="用户信息" min-width="120">
          <template #default="scope">
            <div class="user-info">
              <div class="user-phone">{{ scope.row.phone || '-' }}</div>
              <div class="user-openid">{{ scope.row.openid.substring(0, 12) }}...</div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="商品信息" min-width="200">
          <template #default="scope">
            <div class="product-info">
              <div
                v-for="(item, index) in scope.row.items.slice(0, 2)"
                :key="index"
                class="product-item"
              >
                {{ item.productName }} x{{ item.quantity }}
              </div>
              <div v-if="scope.row.items.length > 2" class="more-items">
                共{{ scope.row.items.length }}件商品
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="订单金额" prop="totalAmount" width="120">
          <template #default="scope">
            <div class="amount-info">
              <div class="total-amount">{{ formatAmount(scope.row.totalAmount) }}</div>
              <div v-if="scope.row.discountAmount > 0" class="discount-amount">
                折扣: -{{ formatAmount(scope.row.discountAmount) }}
              </div>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn label="状态" prop="status" width="100">
          <template #default="scope">
            <ElTag :type="getOrderStatusTagType(scope.row.status)">
              {{ getOrderStatusText(scope.row.status) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="支付方式" prop="paymentMethod" width="100">
          <template #default="scope">
            <ElTag :type="getPaymentMethodTagType(scope.row.paymentMethod)">
              {{ getPaymentMethodText(scope.row.paymentMethod) }}
            </ElTag>
          </template>
        </ElTableColumn>
        <ElTableColumn label="VIP" width="80">
          <template #default="scope">
            <ElTag v-if="scope.row.isVipOrder" type="warning" size="small">VIP</ElTag>
            <span v-else>-</span>
          </template>
        </ElTableColumn>
        <ElTableColumn label="创建时间" prop="createTime" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </ElTableColumn>
        <ElTableColumn fixed="right" label="操作" width="200">
          <template #default="scope">
            <ElSpace :size="8">
              <ElButton type="primary" link @click="showDetailDialog(scope.row)">详情</ElButton>
              <ElButton
                v-if="canShipOrder(scope.row.status)"
                type="success"
                link
                @click="handleShip(scope.row)"
              >
                发货
              </ElButton>
              <ElButton
                v-if="scope.row.status === 'shipped'"
                type="primary"
                link
                @click="handleDeliver(scope.row)"
              >
                确认收货
              </ElButton>
              <ElButton
                v-if="canCompleteOrder(scope.row.status)"
                type="success"
                link
                @click="handleComplete(scope.row)"
              >
                完成
              </ElButton>
              <ElButton
                v-if="canRefundOrder(scope.row.status)"
                type="danger"
                link
                @click="showRefundDialog(scope.row)"
              >
                退款
              </ElButton>
            </ElSpace>
          </template>
        </ElTableColumn>
      </template>
    </ArtTable>

    <!-- 订单详情弹窗 -->
    <ElDialog v-model="detailDialogVisible" title="订单详情" width="800px" align-center>
      <div v-if="currentOrder" class="order-detail">
        <!-- 基本信息 -->
        <ElDescriptions :column="2" border title="订单信息">
          <ElDescriptionsItem label="订单号">
            {{ currentOrder.orderNo }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="订单状态">
            <ElTag :type="getOrderStatusTagType(currentOrder.status)">
              {{ getOrderStatusText(currentOrder.status) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户手机">
            {{ currentOrder.phone }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="用户openid">
            {{ currentOrder.openid }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="支付方式">
            <ElTag :type="getPaymentMethodTagType(currentOrder.paymentMethod)">
              {{ getPaymentMethodText(currentOrder.paymentMethod) }}
            </ElTag>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="是否VIP订单">
            <ElTag v-if="currentOrder.isVipOrder" type="warning">VIP订单</ElTag>
            <span v-else>普通订单</span>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="创建时间">
            {{ formatDate(currentOrder.createTime) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="支付时间">
            {{ currentOrder.paymentTime ? formatDate(currentOrder.paymentTime) : '-' }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <!-- 金额信息 -->
        <ElDescriptions :column="2" border title="金额信息" class="mt-4">
          <ElDescriptionsItem label="原始金额">
            {{ formatAmount(currentOrder.originalAmount) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="折扣金额">
            {{ formatAmount(currentOrder.discountAmount) }}
          </ElDescriptionsItem>
          <ElDescriptionsItem label="实付金额">
            <span class="total-amount">{{ formatAmount(currentOrder.totalAmount) }}</span>
          </ElDescriptionsItem>
          <ElDescriptionsItem label="VIP折扣">
            {{
              calculateVipDiscountAmount(currentOrder.items) > 0
                ? formatAmount(calculateVipDiscountAmount(currentOrder.items))
                : '-'
            }}
          </ElDescriptionsItem>
        </ElDescriptions>

        <!-- 商品列表 -->
        <div class="mt-4">
          <h3>商品列表</h3>
          <ElTable :data="currentOrder.items" border>
            <ElTableColumn label="商品图片" width="80">
              <template #default="scope">
                <ElImage
                  v-if="scope.row.productImage"
                  :src="scope.row.productImage"
                  style="width: 50px; height: 50px"
                  fit="cover"
                />
                <span v-else>-</span>
              </template>
            </ElTableColumn>
            <ElTableColumn label="商品名称" prop="productName" min-width="150" />
            <ElTableColumn label="商品类型" width="100">
              <template #default="scope">
                <ElTag :type="getProductTypeTagType(scope.row.productType)">
                  {{ getProductTypeText(scope.row.productType) }}
                </ElTag>
              </template>
            </ElTableColumn>
            <ElTableColumn label="原价" width="100">
              <template #default="scope">
                {{ formatAmount(scope.row.originalPrice) }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="实价" width="100">
              <template #default="scope">
                {{ formatAmount(scope.row.price) }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="数量" prop="quantity" width="80" />
            <ElTableColumn label="小计" width="100">
              <template #default="scope">
                {{ formatAmount(scope.row.subtotal) }}
              </template>
            </ElTableColumn>
            <ElTableColumn label="VIP折扣" width="100">
              <template #default="scope">
                <ElTag v-if="scope.row.hasVipDiscount" type="warning" size="small">
                  {{
                    scope.row.vipDiscount?.type === 'percent'
                      ? `${scope.row.vipDiscount.value}%`
                      : `¥${(scope.row.vipDiscount?.value || 0) / 100}`
                  }}
                </ElTag>
                <span v-else>-</span>
              </template>
            </ElTableColumn>
          </ElTable>
        </div>

        <!-- 收货地址（仅实物商品） -->
        <div v-if="currentOrder.address" class="mt-4">
          <ElDescriptions :column="1" border title="收货地址">
            <ElDescriptionsItem label="收货人">
              {{ currentOrder.address.name }} - {{ currentOrder.address.phone }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="收货地址">
              {{
                `${currentOrder.address.province}${currentOrder.address.city}${currentOrder.address.district}${currentOrder.address.detail}`
              }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>

        <!-- VIP信息 -->
        <div v-if="currentOrder.vipInfo" class="mt-4">
          <ElDescriptions :column="2" border title="VIP信息">
            <ElDescriptionsItem label="VIP类型">
              {{ currentOrder.vipInfo.type === 'monthly' ? '月度会员' : '年度会员' }}
            </ElDescriptionsItem>
            <ElDescriptionsItem label="有效期">
              {{ currentOrder.vipInfo.duration }}个月
            </ElDescriptionsItem>
            <ElDescriptionsItem label="到期时间">
              {{ formatDate(currentOrder.vipInfo.expireTime) }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>

        <!-- 备注 -->
        <div v-if="currentOrder.remark" class="mt-4">
          <ElDescriptions :column="1" border title="备注信息">
            <ElDescriptionsItem label="备注">
              {{ currentOrder.remark }}
            </ElDescriptionsItem>
          </ElDescriptions>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="detailDialogVisible = false">关闭</ElButton>
        </div>
      </template>
    </ElDialog>

    <!-- 退款处理弹窗 -->
    <ElDialog
      v-model="refundDialogVisible"
      title="处理退款"
      width="500px"
      align-center
      :close-on-click-modal="false"
    >
      <ElForm ref="refundFormRef" :model="refundForm" :rules="refundRules" label-width="100px">
        <ElFormItem label="退款原因" prop="reason">
          <ElInput
            v-model="refundForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入退款原因"
            maxlength="500"
            show-word-limit
          />
        </ElFormItem>
        <ElFormItem label="退款金额" prop="amount">
          <ElInputNumber
            v-model="refundAmountYuan"
            :min="0"
            :max="currentOrder ? centToYuan(currentOrder.totalAmount) : 0"
            :precision="2"
            style="width: 100%"
            placeholder="留空则全额退款"
            @change="handleRefundAmountChange"
          />
          <div class="amount-tip">
            订单总金额：{{ currentOrder ? formatAmount(currentOrder.totalAmount) : '¥0.00' }}
          </div>
        </ElFormItem>
      </ElForm>
      <template #footer>
        <div class="dialog-footer">
          <ElButton @click="refundDialogVisible = false">取消</ElButton>
          <ElButton type="danger" @click="handleRefund" :loading="submitLoading">
            确认退款
          </ElButton>
        </div>
      </template>
    </ElDialog>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import {
    OrderService,
    type Order,
    type OrderListParams,
    getOrderStatusText,
    getOrderStatusTagType,
    getPaymentMethodText,
    getPaymentMethodTagType,
    getProductTypeText,
    getProductTypeTagType,
    formatAmount,
    centToYuan,
    yuanToCent,
    canShipOrder,
    canCompleteOrder,
    canRefundOrder,
    calculateVipDiscountAmount
  } from '@/api/orderApi'

  defineOptions({ name: 'OrderManage' })

  // 响应式数据
  const loading = ref(false)
  const submitLoading = ref(false)
  const detailDialogVisible = ref(false)
  const refundDialogVisible = ref(false)
  const refundFormRef = ref<FormInstance>()
  const currentOrder = ref<Order | null>(null)

  // 查询表单
  const queryForm = reactive<OrderListParams>({
    keyword: '',
    status: undefined,
    paymentMethod: undefined,
    isVipOrder: undefined,
    productType: undefined,
    hasVipDiscount: undefined,
    startTime: undefined,
    endTime: undefined,
    minAmount: undefined,
    maxAmount: undefined,
    sort: 'createTime',
    order: 'desc'
  })

  // 分页数据
  const pagination = reactive({
    page: 1,
    size: 20,
    total: 0
  })

  // 订单列表
  const orderList = ref<Order[]>([])

  // 日期范围
  const dateRange = ref<[string, string] | null>(null)

  // 金额范围（元）
  const minAmountYuan = ref<number | undefined>(undefined)
  const maxAmountYuan = ref<number | undefined>(undefined)

  // 退款表单
  const refundForm = reactive({
    reason: '',
    amount: undefined as number | undefined
  })

  // 退款金额（元）
  const refundAmountYuan = ref<number | undefined>(undefined)

  // 退款表单验证规则
  const refundRules = reactive<FormRules>({
    reason: [
      { required: true, message: '请输入退款原因', trigger: 'blur' },
      { min: 5, max: 500, message: '长度在 5 到 500 个字符', trigger: 'blur' }
    ]
  })

  // 获取订单列表
  const getOrderList = async () => {
    try {
      loading.value = true
      const params: OrderListParams = {
        page: pagination.page,
        size: pagination.size,
        ...queryForm
      }
      // 移除空值
      Object.keys(params).forEach((key) => {
        if (
          params[key as keyof OrderListParams] === '' ||
          params[key as keyof OrderListParams] === undefined
        ) {
          delete params[key as keyof OrderListParams]
        }
      })

      const response = await OrderService.getOrderList(params)
      if (response.code === 200) {
        orderList.value = response.data
        pagination.total = response.total
      } else {
        ElMessage.error(response.message)
      }
    } catch (error) {
      ElMessage.error('获取订单列表失败')
      console.error('获取订单列表失败:', error)
      orderList.value = []
      pagination.total = 0
    } finally {
      loading.value = false
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    getOrderList()
  }

  // 重置查询
  const resetQuery = () => {
    Object.assign(queryForm, {
      keyword: '',
      status: undefined,
      paymentMethod: undefined,
      isVipOrder: undefined,
      productType: undefined,
      hasVipDiscount: undefined,
      startTime: undefined,
      endTime: undefined,
      minAmount: undefined,
      maxAmount: undefined,
      sort: 'createTime',
      order: 'desc'
    })
    dateRange.value = null
    minAmountYuan.value = undefined
    maxAmountYuan.value = undefined
    pagination.page = 1
    getOrderList()
  }

  // 分页处理
  const handleSizeChange = (val: number) => {
    pagination.size = val
    pagination.page = 1
    getOrderList()
  }

  const handleCurrentChange = (val: number) => {
    pagination.page = val
    getOrderList()
  }

  // 日期范围变化处理
  // const handleDateRangeChange = (dates: [string, string] | null) => {
  //   if (dates) {
  //     queryForm.startTime = dates[0]
  //     queryForm.endTime = dates[1]
  //   } else {
  //     queryForm.startTime = undefined
  //     queryForm.endTime = undefined
  //   }
  // }

  // 金额范围变化处理
  // const handleAmountChange = () => {
  //   queryForm.minAmount = minAmountYuan.value ? yuanToCent(minAmountYuan.value) : undefined
  //   queryForm.maxAmount = maxAmountYuan.value ? yuanToCent(maxAmountYuan.value) : undefined
  // }

  // 显示订单详情
  const showDetailDialog = async (row: Order) => {
    try {
      const response = await OrderService.getOrderDetail(row._id!)
      currentOrder.value = response.data
      detailDialogVisible.value = true
    } catch (error) {
      ElMessage.error('获取订单详情失败')
      console.error('获取订单详情失败:', error)
    }
  }

  // 发货
  const handleShip = (row: Order) => {
    ElMessageBox.confirm('确定将该订单标记为已发货吗？', '发货确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      try {
        await OrderService.updateOrderStatus(row._id!, { status: 'shipped' })
        ElMessage.success('发货成功')
        getOrderList()
      } catch (error) {
        ElMessage.error('发货失败')
        console.error('发货失败:', error)
      }
    })
  }

  // 确认收货
  const handleDeliver = (row: Order) => {
    ElMessageBox.confirm('确定将该订单标记为已收货吗？', '收货确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'primary'
    }).then(async () => {
      try {
        await OrderService.updateOrderStatus(row._id!, { status: 'delivered' })
        ElMessage.success('确认收货成功')
        getOrderList()
      } catch (error) {
        ElMessage.error('确认收货失败')
        console.error('确认收货失败:', error)
      }
    })
  }

  // 完成订单
  const handleComplete = (row: Order) => {
    ElMessageBox.confirm('确定将该订单标记为已完成吗？', '完成订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }).then(async () => {
      try {
        await OrderService.updateOrderStatus(row._id!, { status: 'completed' })
        ElMessage.success('订单完成成功')
        getOrderList()
      } catch (error) {
        ElMessage.error('订单完成失败')
        console.error('订单完成失败:', error)
      }
    })
  }

  // 显示退款弹窗
  const showRefundDialog = (row: Order) => {
    currentOrder.value = row
    refundForm.reason = ''
    refundForm.amount = undefined
    refundAmountYuan.value = undefined
    refundDialogVisible.value = true
  }

  // 退款金额变化处理
  const handleRefundAmountChange = () => {
    refundForm.amount = refundAmountYuan.value ? yuanToCent(refundAmountYuan.value) : undefined
  }

  // 处理退款
  const handleRefund = async () => {
    if (!refundFormRef.value || !currentOrder.value) return

    try {
      await refundFormRef.value.validate()
      submitLoading.value = true

      await OrderService.refundOrder(currentOrder.value._id!, {
        reason: refundForm.reason,
        amount: refundForm.amount
      })

      ElMessage.success('退款处理成功')
      refundDialogVisible.value = false
      getOrderList()
    } catch (error) {
      ElMessage.error('退款处理失败')
      console.error('退款处理失败:', error)
    } finally {
      submitLoading.value = false
    }
  }

  // 导出订单
  const exportOrders = () => {
    ElMessage.info('导出功能开发中...')
  }

  // 格式化时间
  const formatDate = (timestamp?: number) => {
    if (!timestamp) return '-'

    try {
      const date = new Date(timestamp * 1000)
      if (isNaN(date.getTime())) {
        return timestamp.toString()
      }

      return date
        .toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        })
        .replace(/\//g, '-')
    } catch (error) {
      console.error('时间格式化错误:', error, timestamp)
      return timestamp?.toString() || '-'
    }
  }

  // 生命周期
  onMounted(() => {
    getOrderList()
  })
</script>

<style lang="scss" scoped>
  .page-content {
    .user-info {
      .user-phone {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .user-openid {
        margin-top: 2px;
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }

    .product-info {
      .product-item {
        margin-bottom: 2px;
        font-size: 12px;
        color: var(--el-text-color-regular);
      }

      .more-items {
        font-size: 12px;
        color: var(--el-text-color-secondary);
      }
    }

    .amount-info {
      .total-amount {
        font-weight: 500;
        color: var(--el-text-color-primary);
      }

      .discount-amount {
        margin-top: 2px;
        font-size: 12px;
        color: var(--el-color-success);
      }
    }

    .order-detail {
      .mt-4 {
        margin-top: 16px;
      }

      .total-amount {
        font-weight: bold;
        color: var(--el-color-danger);
      }
    }

    .amount-tip {
      margin-top: 4px;
      font-size: 12px;
      color: var(--el-text-color-secondary);
    }
  }
</style>
